package com.chen.blue.config;

import com.chen.blue.redis.service.RedisService;
import com.chen.blue.security.filter.TokenAuthenticationFilter;
import com.chen.blue.security.handle.AuthorizationFailHandler;
import com.chen.blue.service.system.*;
import com.chen.blue.sysconfig.SystemConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.annotation.Resource;

/**
 * Created By CLT On 2023/10/30.
 */
@SuppressWarnings("all")
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Resource
    private AuthenticationEntryPoint authenticationEntryPoint;

    @Resource
    private AccessDeniedHandler accessDeniedHandler;

    @Resource
    private RedisService iRedisService;

    @Resource
    private IUsersService userService;

    @Resource
    private IDeptService iDeptService;

    @Resource
    private IDataScopeUserDeptService iDataScopeUserDeptService;

    @Resource
    private IUserRoleService iUserRoleService;

    @Resource
    private IMenuRoleService iMenuRoleService;

    @Resource
    private SystemConfig systemConfig;

    /**
     * security配置类
     */
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {

        httpSecurity
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .exceptionHandling().authenticationEntryPoint(authorizationFailHandler)
                .and()
                /**
                 * 请求认证
                 */
                .authorizeRequests()
                // 静态资源放行
                .antMatchers(
                        HttpMethod.GET,
                        "/*.html",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js"
                ).permitAll()
                // swagger文档放行
                .antMatchers("/doc.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs").permitAll()
                // 数据源管理
                .antMatchers("/druid/**").permitAll()
                // 请求放行
                .antMatchers("/admin/auth/login", "/admin/auth/logout").permitAll()
                .antMatchers("/admin/test/**").permitAll()
                // 本地资源放行
                .antMatchers("/profile/**").anonymous()
                // 其他请求需要认证
                .anyRequest().authenticated()
                .and()
                .headers().frameOptions().disable()
                .and()
                // 配置认证失败和权限不足的自定义处理类
                //  .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).accessDeniedHandler(accessDeniedHandler)
                //  .and()
                // 添加token验证过滤器
                .addFilterBefore(usernamePasswordAuthenticationToken(), BasicAuthenticationFilter.class);

    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

    @Bean
    public BasicAuthenticationFilter usernamePasswordAuthenticationToken() throws Exception {
        return new TokenAuthenticationFilter(authenticationManagerBean(), iRedisService, userService, iDeptService, iDataScopeUserDeptService, iUserRoleService, iMenuRoleService, systemConfig);
    }

    /**
     * 认证失败处理类
     */
    @Resource
    private AuthorizationFailHandler authorizationFailHandler;

    /**
     * 基于数据库自定义认证
     */
    @Autowired
    private UserDetailsService userDetailsService;

}
